<?php

namespace app\modules\api\controllers;

use app\models\AgentLoginForm;
use app\models\ApiException;
use app\models\SubUser;
use app\models\SubUserLoginForm;
use app\models\User;
use app\models\UserLoginForm;
use app\models\Util;
use app\models\AgentAccount;
use app\models\Agent;
use app\models\UserAccount;
use Yii;
use yii\base\Exception;

/**
 * 用户处理
 * Class UserController
 * @package app\modules\api\controllers
 */
class UserController extends BaseController
{
    /**
     * 用户登录
     * 输入
     * {
     *     type,
     *     username,
     *     password
     * }
     * 输出
     * {
     *     token
     * }
     * @throws ApiException
     */
    public function actionLogin()
    {
        $this->checkJson([
            [['username', 'password'], 'required', 'message' => '缺少必要参数。'],
        ]);

        $type = $this->json('type', 'user');
        if ($type == 'agent') {
            $model = new AgentLoginForm();
            $model->setAttributes($this->json);
            if (!$model->login()) {
                throw new ApiException('USER_LOGIN', '登录失败，请检查登录参数。', $model->errors);
            }
            $agent = $model->getAgent();
            $token = $agent->generateToken($this->app_id);
        } elseif ($type == 'user') {
            $username = $this->json('username');
            if (!preg_match('/^(.+)@(\d+)$/', $username)) { // 子用户
                $model = new UserLoginForm();
            } else {
                $this->json['username'] = preg_replace('/^(.+)@(\d+)$/', '$1', $username);
                $this->json['uid'] = preg_replace('/^(.+)@(\d+)$/', '$2', $username);
                $model = new SubUserLoginForm();
            }
            $model->setAttributes($this->json);
            if (!$model->login()) {
                throw new ApiException('USER_LOGIN', '登录失败，请检查登录参数。', $model->errors);
            }
            $user = $model->getUser();
            $token = $user->generateToken($this->app_id);
        } else {
            throw new ApiException('PARAM', '登录类型错误。');
        }

        return [
            'token' => $token,
        ];
    }
    public function actionAccount()
    {   
        $this->checkJson([
            [['username', 'password'], 'required', 'message' => '缺少必要参数。'],
        ]);
        $user = $this->loginUser();
        $type = $this->json('type', 'agent');
        if ($type == 'agent') {
            //$model = new AgentAccount();
            // $model->setAttributes($this->json);
            // if (!$model->login()) {
            //     throw new ApiException('USER_LOGIN', '登录失败，请检查登录参数。', $model->errors);
            // }
            // $agent = $model->getAgent();
            // $token = $agent->generateToken($this->app_id);
            $agent = Agent::findOne(['username'=>$this->json('username')]);
            $user_name = $agent['username'];
            if(empty($agent)){
                $user_name = "没有找到该用户";
            }
            $account = AgentAccount::findOne(['agent_id'=>$agent['id']]);
            $user_money = $account['money'];
            if(empty($account)){
                $user_money = 0;
            }
        } 

        return [
            'type'     => $type,
            'username' => $user_name,
            'money'    => $user_money
        ];
    }
    /**
     * 重新获取Token
     * 输入
     * {}
     * 输出
     * {
     *     token
     * }
     * @throws ApiException
     */
    public function actionNewToken()
    {
        if (!Yii::$app->user->isGuest) {
            $user = User::findOne(['id' => Yii::$app->user->id]);
            return [
                'token' => $user->generateToken($this->app_id),
            ];
        }
        if (!Yii::$app->subUser->isGuest) {
            $subUser = SubUser::findOne(['id' => Yii::$app->subUser->id]);
            return [
                'token' => $subUser->generateToken($this->app_id),
            ];
        }
        $token = Yii::$app->request->headers->get('token');
        if (empty($token)) {
            $token = $this->get('token');
        }
        if (empty($token)) {
            throw new ApiException('NOT_FOUND', '没有找到Token参数。');
        }
        try {
            $payloadJson = Util::checkJWT($token);
            if (isset($payloadJson['uid'])) {
                $user = User::findOne(['id' => $payloadJson['uid']]);
                return [
                    'token' => $user->generateToken($this->app_id),
                ];
            } elseif ($payloadJson['sub_uid']) {
                $subUser = SubUser::findOne(['id' => $payloadJson['sub_uid']]);
                return [
                    'token' => $subUser->generateToken($this->app_id),
                ];
            } else {
                throw new ApiException('TOKEN', 'TOKEN错误。');
            }
        } catch (Exception $e) {
            throw new ApiException('TOKEN', $e->getMessage());
        }
    }
}
